//
//  SHPhotoBrowser.m
//  Tradeaider
//
//  Created by 王方伟 on 2017/7/12.
//  Copyright © 2017年 Shinyhub. All rights reserved.
//

#import "SHPhotoBrowser.h"
#import "SHScaleAnimatorCoordinator.h"
#import "SHPhotoBrowserLayout.h"
#import "SHPhotoBrowserCell.h"
#import "UIView+Extension.h"
#import "SHScaleAnimator.h"


@interface SHPhotoBrowser ()<UICollectionViewDataSource, UICollectionViewDelegate, UIViewControllerTransitioningDelegate, PhotoBrowserCellDelegate>
@property (strong, nonatomic) UIViewController *presentingVC;
@property (weak, nonatomic) id<PhotoBrowserDelegate> delegate;
@property (assign, nonatomic) NSInteger currentIndex;

@property (weak, nonatomic) UICollectionView *collectionView;
@property (weak, nonatomic) SHPhotoBrowserLayout *flowLayout;

@property (strong, nonatomic) SHScaleAnimatorCoordinator *animatorCoordinator;
@property (strong, nonatomic) SHScaleAnimator *presentationAnimator;
@property (strong, nonatomic) UIView *relatedView;

@property (strong, nonatomic) PhotoBrowserConfig *config;
@property (weak, nonatomic) UIButton *moreButton;
@end

@implementation SHPhotoBrowser
static NSString *const ID = @"SHPhotoBrowserCell";

+ (instancetype)photoBrowser:(UIViewController *)presentingVC delegate:(id<PhotoBrowserDelegate>)delegate{
    SHPhotoBrowser *phtotBrowser = [[SHPhotoBrowser alloc] init];
    phtotBrowser.presentingVC = presentingVC;
    phtotBrowser.delegate = delegate;
    return phtotBrowser;
}


- (UIView *)relatedView{
    return [_delegate photoBrowser:self showViewIndex:_currentIndex];;
}


- (CGFloat)photoSpacing{
    if (_photoSpacing == 0) {
        return 20;
    }
    return _photoSpacing;
}

+ (void)show:(UIViewController *)presentingVC delegate:(id<PhotoBrowserDelegate>)delegate index:(NSInteger)index configBlock:(void (^)(PhotoBrowserConfig *))configBlock{
    SHPhotoBrowser *photoBrowser = [SHPhotoBrowser photoBrowser:presentingVC delegate:delegate];
    [photoBrowser show:index];
    if (configBlock) {
        configBlock(photoBrowser.config);
        [photoBrowser updateConfig];
    }
}

- (void)show:(NSInteger)index{
    self.currentIndex = index;

    self.transitioningDelegate = self;
    self.modalPresentationStyle = UIModalPresentationCustom;
    self.modalPresentationCapturesStatusBarAppearance = YES;
    [_presentingVC presentViewController:self animated:YES completion:nil];
}

- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        SHPhotoBrowserLayout *flowLayout = [[SHPhotoBrowserLayout alloc] init];
        flowLayout.itemSize = self.view.bounds.size;
        flowLayout.minimumLineSpacing = self.photoSpacing;
        
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([SHPhotoBrowserCell class]) bundle:[NSBundle bundleForClass:[SHPhotoBrowserCell class]]] forCellWithReuseIdentifier:ID];
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.showsHorizontalScrollIndicator = FALSE;
        collectionView.showsVerticalScrollIndicator = FALSE;
        collectionView.decelerationRate = UIScrollViewDecelerationRateFast;
        collectionView.dataSource = self;
        collectionView.delegate = self;
        [self.view addSubview:collectionView];
        _collectionView = collectionView;
        _flowLayout = flowLayout;
    }
    return _collectionView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.collectionView reloadData];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
    [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:FALSE];
    [self.collectionView layoutIfNeeded];
    SHPhotoBrowserCell *cell = (SHPhotoBrowserCell *)[_collectionView cellForItemAtIndexPath:indexPath];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:cell.imageView.image];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    _presentationAnimator.endView = cell.imageView;
    _presentationAnimator.scaleView = imageView;
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if (self.config.isShowMoreButton) {
        CGSize size = self.config.moreNormalImage.size;
        CGFloat centerX = self.view.width - 10 - size.width * 0.5;
        CGFloat centerY = 20 + size.height * 0.5 + 10;
        self.moreButton.size = size;
        self.moreButton.center = CGPointMake(centerX, centerY);
    }
}

#pragma mark 修改配置
- (void)updateConfig{
    if (self.config.isShowMoreButton) {
        [self moreButton];
    }
}

- (void)onClickMoreItem{
    if ([_delegate respondsToSelector:@selector(onTouchMore:)]) {
        [_delegate onTouchMore:self];
    }
}

#pragma mark UICollectionView 代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [_delegate numberOfPhotos:self];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SHPhotoBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    UIImage *placeholderImage = [_delegate photoBrowser:self index:indexPath.row];
    NSURL *hightURL = [self getHightURL:indexPath.row];
    NSURL *originalURL = [self getOriginalURL:indexPath.row];
    [cell setPlaceholderImage:placeholderImage hightUrl:hightURL originalUrl:originalURL];
    cell.delegate = self;
    return cell;
}

- (NSURL *)getOriginalURL:(NSInteger)index{
    if ([_delegate respondsToSelector:@selector(photoBrowser:originalQualityUrlIndex:)]) {
        return [_delegate photoBrowser:self originalQualityUrlIndex:index];
    }
    return nil;
}

- (NSURL *)getHightURL:(NSInteger)index{
    if ([_delegate respondsToSelector:@selector(photoBrowser:highQualityUrlIndex:)]) {
        return [_delegate photoBrowser:self highQualityUrlIndex:index];
    }
    return nil;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGFloat offsetX = scrollView.contentOffset.x;
    CGFloat width = scrollView.bounds.size.width;
    self.currentIndex = (NSInteger)(offsetX / width);
    [_animatorCoordinator updateCurrentHiddenView:self.relatedView];
}

#pragma mark 转场动画代理
- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source{
    SHScaleAnimatorCoordinator *coordinator = [[SHScaleAnimatorCoordinator alloc] initWithPresentedViewController:presented presentingViewController:presenting];
    _animatorCoordinator = coordinator;
    [_animatorCoordinator updateCurrentHiddenView:self.relatedView];
    return coordinator;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    SHPhotoBrowserCell *cell = _collectionView.visibleCells.firstObject;
    UIImageView *imageView = [[UIImageView alloc] initWithImage:cell.imageView.image];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    SHScaleAnimator *animator = [SHScaleAnimator scaleAnimatorWithStartView:self.relatedView endView:cell.imageView scaleView:imageView];
    _presentationAnimator = animator;
    return animator;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    SHPhotoBrowserCell *cell = _collectionView.visibleCells.firstObject;
    UIImageView *imageView = [[UIImageView alloc] initWithImage:cell.imageView.image];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    SHScaleAnimator *animator = [SHScaleAnimator scaleAnimatorWithStartView:cell.imageView endView:self.relatedView scaleView:imageView];
    return animator;
}



#pragma mark PhotoBrowserCell 代理
- (void)onClickSingleTap:(SHPhotoBrowserCell *)cell{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)onPanTap:(SHPhotoBrowserCell *)cell scale:(CGFloat)scale{
    CGFloat alpha = scale * scale;
    _animatorCoordinator.alpha = alpha;
}

- (void)photoBrowserCell:(SHPhotoBrowserCell *)cell didLongPressWith:(UIImage *)image{
    if ([_delegate respondsToSelector:@selector(photoBrowser:didLongPressIndex:image:)]) {
        NSIndexPath *indexPath = [_collectionView indexPathForCell:cell];
        [_delegate photoBrowser:self didLongPressIndex:indexPath.row image:image];
    }
}


#pragma mark Private
- (PhotoBrowserConfig *)config{
    if (_config == nil) {
        _config = [PhotoBrowserConfig defaultConfig];
    }
    return _config;
}

- (UIButton *)moreButton{
    if (_moreButton == nil) {
        UIButton *moreButton = [[UIButton alloc] init];
        [moreButton setImage:self.config.moreNormalImage forState:UIControlStateNormal];
        [moreButton setImage:self.config.morePressedImage forState:UIControlStateHighlighted];
        [moreButton addTarget:self action:@selector(onClickMoreItem) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:moreButton];
        [self.view bringSubviewToFront:moreButton];
        _moreButton = moreButton;
    }
    return _moreButton;
}
@end
